<?php
require_once '../library/Util/Util.php';
require_once '../library/Util/Pagination.php';
class BlogController extends Zend_Controller_Action{

	public function init(){
		parent::init();
		$request = $this->getRequest();
		$action = $request->getActionName();
		$uid = $request->getParam('uid', null);

		if(empty($uid) && !empty($_SESSION['logginUser'])){
			unset($_SESSION['logginUser']);
		}else if(!empty($uid) && ( (empty($_SESSION['logginUser']) || ($_SESSION['logginUser']['uid'] != $uid)))){
			unset($_SESSION['logginUser']);
			$result = Util::ssoLogin('http://localhost:3000/sso', '/index/auth',array('nickname', 'fullname'), array('email'));
			if($result != ""){
				$_SESSION['msg']['action'] = 'loginfail';
				$this->_redirect('/error');							
			}
			exit();			
		}else if(!empty($uid) && !empty($_SESSION['logginUser'])){
			$check = Util::ssoCheckState('http://localhost:3000/sso', $_SESSION['logginUser']['uid'], $_SESSION['logginUser']['sid']);
			if(!$check){
				unset($_SESSION['logginUser']);
			}
		}

		if($action != 'index' && $action != 'detail'){
			if(empty($_SESSION['logginUser']) || empty($uid)){
				if($request->isPost()){
					$_SESSION['msg']['action'] = 'loginfail';
					$this->_redirect('/error');
				}else{
					$result = Util::ssoLogin('http://localhost:3000/sso', '/index/auth',array('nickname', 'fullname'), array('email'));
					if($result != ""){
						$_SESSION['msg']['action'] = 'loginfail';
						$this->_redirect('/error');							
					}
					exit();
				}
			}else if($_SESSION['logginUser']['uid'] != $uid){
				unset($_SESSION['logginUser']);
				$_SESSION['msg']['action'] = 'loginfail';
				$this->_redirect('/error');					
			}
			
		}
	}

	public function indexAction(){
		/*
		 * Khai bao cho header
		 */
		$this->view->headLink()->appendStylesheet('/css/bootstrap.min.css','screen',true);
		$this->view->headLink()->appendStylesheet('/css/bootstrap-responsive.min.css','screen',true);
		$this->view->headLink()->appendStylesheet('/css/style.css','screen',true);

		$this->view->headScript()->appendFile('/js/jquery-1.8.3.min.js');	
		$this->view->headScript()->appendFile('http://localhost:3000/js/soCore.js');
		$this->view->headScript()->appendFile('/js/bootstrap.min.js');

		$request = $this->getRequest();
		$userID = $request->getParam("usid", null);
		$page = $request->getParam("page", 1);
		$limit = 3;
		$tbBlogs = new User_Model_Blogs();

		$userBlogs = $tbBlogs->getUserBlogsInPage($userID, $page, $limit);
		$totalBlogs = $tbBlogs->countAllUserBlogs($userID);

		foreach ($userBlogs as &$blog) {
			$blog['content'] = Util::split_words($blog['content'], 200, "...");
			$blog['title'] = Util::split_words($blog['title'], 20, "...");
			$blog['created_date'] = Util::change_int_to_date($blog['created_date']);
		}


		$pagination = new Pagination();
		$pagination->init("/blog/index/usid/".$userID."/page/", $totalBlogs, $limit, $page);
		$this->view->assign('pagination', $pagination->renderFront());	

		$listUid = array('lst_uid' => $userID);
		$oauthData = Util::oauthGetApi('http://localhost:3000/api/v1/users', $listUid, 'GET');
		
		$userInfo = array();
		if(!empty($oauthData) && is_array($oauthData)){
			$userInfo['fullname']   = $oauthData[$userID]['fullname'];
			$userInfo['uid']		= $userID;
			$userInfo['avatar']		= $oauthData[$userID]['avatar'];
			$userInfo['profile_url']		= $oauthData[$userID]['profile_url'];
		}

		if(isset($_SESSION['logginUser']) && ($userID == $_SESSION['logginUser']['uid'])){
			$this->view->assign('owner', true);
		}else{
			$this->view->assign('owner', false);
		}
		$this->view->headTitle()->append('Blog của '.$userInfo['fullname']);
		$this->view->assign('userBlogs', $userBlogs);
		$this->view->assign('userInfo', $userInfo);
		$this->view->assign('totalBlog', $totalBlogs);
		$this->view->assign('usid', $userID);
	}

	public function detailAction(){
		/*
		 * Khai bao cho header
		 */
		$this->view->headLink()->appendStylesheet('/css/bootstrap.min.css','screen',true);
		$this->view->headLink()->appendStylesheet('/css/bootstrap-responsive.min.css','screen',true);
		$this->view->headLink()->appendStylesheet('/css/style.css','screen',true);

		$this->view->headScript()->appendFile('/js/jquery-1.8.3.min.js');	
		$this->view->headScript()->appendFile('http://localhost:3000/js/soCore.js');
		$this->view->headScript()->appendFile('/js/bootstrap.min.js');

		$request = $this->getRequest();
		$bid = $request->getParam("bid", null);

		$tbBlogs = new User_Model_Blogs();

		$blog = $tbBlogs->getBlogById($bid);
		if(empty($blog)){
			$_SESSION['msg']['action'] = 'notfound';
			$this->_redirect('/error');
		}

		if(isset($_SESSION['logginUser']) && ($blog[0]['uid'] == $_SESSION['logginUser']['uid'])){
			$this->view->assign('owner', true);
		}else{
			$this->view->assign('owner', false);
		}

		$blog[0]['created_date'] = Util::change_int_to_date($blog[0]['created_date']);
		$userID = $blog[0]['uid'];
		$totalBlogs = $tbBlogs->countAllUserBlogs($userID);

		$listUid = array('lst_uid' => $userID);
		$oauthData = Util::oauthGetApi('http://localhost:3000/api/v1/users', $listUid, 'GET');
		
		$userInfo = array();
		if(!empty($oauthData) && is_array($oauthData)){
			$userInfo['fullname']   = $oauthData[$userID]['fullname'];
			$userInfo['uid']		= $userID;
			$userInfo['avatar']		= $oauthData[$userID]['avatar'];
			$userInfo['profile_url']		= $oauthData[$userID]['profile_url'];
		}

		$this->view->headTitle()->append('Blog - '.$blog[0]['title']);
		$this->view->assign('usid', $userID);
		$this->view->assign('bid' , $blog[0]['id']);
		$this->view->assign('bTitle', Util::split_words($blog[0]['title'], 75, "..."));
		$this->view->assign('blog', $blog[0]);
		$this->view->assign('userInfo', $userInfo);
		$this->view->assign('totalBlog', $totalBlogs);		
	}

	public function addAction(){
		/*
		 * Khai bao cho header
		 */
		$this->view->headTitle()->append('Viết blog');
		$this->view->headLink()->appendStylesheet('/css/bootstrap.min.css','screen',true);
		$this->view->headLink()->appendStylesheet('/css/bootstrap-responsive.min.css','screen',true);
		$this->view->headLink()->appendStylesheet('/css/style.css','screen',true);

		$this->view->headScript()->appendFile('/js/jquery-1.8.3.min.js');	
		$this->view->headScript()->appendFile('http://localhost:3000/js/soCore.js');
		$this->view->headScript()->appendFile('/js/bootstrap.min.js');
		$this->view->headScript()->appendFile('/js/ckeditor/ckeditor.js');	

		$request = $this->getRequest();
		$uid = $_SESSION['logginUser']['uid'];
		$tbBlogs = new User_Model_Blogs();
		$error = array();

		$title = null;
		$content = null;
		$image = '/img/blog-300x255.jpg';

		if ($request->isPost()) 
		{
		    $title = $request->getParam("title", null);
		    $content = $request->getParam("content", null);
		    if(empty($title)){
		    	$error['title'] = "Tiêu đề không được bỏ trống !";
		    }else if(strlen($title) > 100){
		    	$error['title'] = "Tiêu đề không được quá 100 kí tự !";
		    }

		    if(empty($content)){
				$error['content'] = "Nội dung không được bỏ trống !";
		    }

		    if(empty($error)){
				$check_avatar = 0;
				if( $_FILES["image"]["name"] !="")
				{
					$allowedExts = array("jpg", "jpeg", "gif", "png");
					$extension = explode(".", $_FILES["image"]["name"]);
					/*print_r($extension[1]);
					print_r($_FILES["image"]["type"]);
					print_r($_FILES["image"]["size"]);die;*/
					if ((($_FILES["image"]["type"] == "image/gif")
					|| ($_FILES["image"]["type"] == "image/jpeg")
					|| ($_FILES["image"]["type"] == "image/png")
					|| ($_FILES["image"]["type"] == "image/pjpeg"))
					&& ($_FILES["image"]["size"] < 400000)
					&& in_array($extension[1], $allowedExts))
					  {
					  if ($_FILES["image"]["type"] > 0)
						{
							$error['image'] = "Xuất hiện lỗi trong quá trình upload";
						}
					  else
						{
							$t = time();
						  move_uploaded_file($_FILES["image"]["tmp_name"],
						  $_SERVER['DOCUMENT_ROOT']."/img/blog_img/user_".$uid."_".$t."_". $_FILES["image"]["name"]);
						  $image = "/img/blog_img/user_".$uid."_".$t."_". $_FILES["image"]["name"];
						  $check_avatar = 1;
						}
					  }
					else
					  {
					  	$error['image'] = "Hình đại diện không hợp lệ";
					  }
				}
				else
				{
					$check_avatar = 1;
				}

				if($check_avatar == 1){
					$result = $tbBlogs->insertBlog($uid, $title, $content, $image);
					if($result > 0){
						$_SESSION['msg']['result'] = 1;						
					}else{
						$_SESSION['msg']['result'] = 0;
					}
					$_SESSION['msg']['action'] = 'add';
					$_SESSION['msg']['id']	= $result;
					$this->_redirect('/error');
				}
			}		    
		    
		} 

		$totalBlogs = $tbBlogs->countAllUserBlogs($uid);

		$listUid = array('lst_uid' => $uid);
		$oauthData = Util::oauthGetApi('http://localhost:3000/api/v1/users', $listUid, 'GET');
		
		$userInfo = array();
		if(!empty($oauthData) && is_array($oauthData)){
			$userInfo['fullname']   = $oauthData[$uid]['fullname'];
			$userInfo['uid']		= $uid;
			$userInfo['avatar']		= $oauthData[$uid]['avatar'];
			$userInfo['profile_url'] = $oauthData[$uid]['profile_url'];
		}

		$this->view->assign('totalBlog', $totalBlogs);
		$this->view->assign('error', $error);
		$this->view->assign('uid', $uid);
		$this->view->assign('usid', $uid);
		$this->view->assign('userInfo', $userInfo);
		$this->view->assign('title', $title);
		$this->view->assign('content', $content);
				
	}

	public function editAction(){
		/*
		 * Khai bao cho header
		 */
		$this->view->headTitle()->append('Viết blog');
		$this->view->headLink()->appendStylesheet('/css/bootstrap.min.css','screen',true);
		$this->view->headLink()->appendStylesheet('/css/bootstrap-responsive.min.css','screen',true);
		$this->view->headLink()->appendStylesheet('/css/style.css','screen',true);

		$this->view->headScript()->appendFile('/js/jquery-1.8.3.min.js');	
		$this->view->headScript()->appendFile('http://localhost:3000/js/soCore.js');
		$this->view->headScript()->appendFile('/js/bootstrap.min.js');
		$this->view->headScript()->appendFile('/js/ckeditor/ckeditor.js');	

		$request = $this->getRequest();
		$uid = $_SESSION['logginUser']['uid'];
		$bid = $request->getParam("bid", null);
		$tbBlogs = new User_Model_Blogs();

		$blog = $tbBlogs->getBlogById($bid);
		if(empty($blog)){
			$_SESSION['msg']['action'] = 'notfound';			
			$this->_redirect('/error');
		}

		$error = array();

		$title = $blog[0]['title'];
		$content = $blog[0]['content'];
		$image = $blog[0]['image'];

		if ($request->isPost()) 
		{
		    $title = $request->getParam("title", null);
		    $content = $request->getParam("content", null);
		    if(empty($title)){
		    	$error['title'] = "Tiêu đề không được bỏ trống !";
		    }else if(strlen($title) > 100){
		    	$error['title'] = "Tiêu đề không được quá 100 kí tự !";
		    }

		    if(empty($content)){
				$error['content'] = "Nội dung không được bỏ trống !";
		    }

		    if(empty($error)){
				$check_avatar = 0;
				if( $_FILES["image"]["name"] !="")
				{
					$allowedExts = array("jpg", "jpeg", "gif", "png");
					$extension = explode(".", $_FILES["image"]["name"]);
					if ((($_FILES["image"]["type"] == "image/gif")
					|| ($_FILES["image"]["type"] == "image/jpeg")
					|| ($_FILES["image"]["type"] == "image/png")
					|| ($_FILES["image"]["type"] == "image/pjpeg"))
					&& ($_FILES["image"]["size"] < 400000)
					&& in_array($extension[1], $allowedExts))
					  {
					  if ($_FILES["image"]["type"] > 0)
						{
							$error['image'] = "Xuất hiện lỗi trong quá trình upload";
						}
					  else
						{
							$t = time();
						  move_uploaded_file($_FILES["image"]["tmp_name"],
						  $_SERVER['DOCUMENT_ROOT']."/img/blog_img/user_".$uid."_".$t."_". $_FILES["image"]["name"]);
						  $image = "/img/blog_img/user_".$uid."_".$t."_". $_FILES["image"]["name"];
						  $check_avatar = 1;
						}
					  }
					else
					  {
					  	$error['image'] = "Hình đại diện không hợp lệ";
					  }
				}
				else
				{
					$check_avatar = 1;
				}

				if($check_avatar == 1){
					$result = $tbBlogs->updateBlog($bid, $title, $content, $image);
					if($result > 0){
						$_SESSION['msg']['result'] = 1;
					}else{
						$_SESSION['msg']['result'] = 0;
					}
					$_SESSION['msg']['action'] = 'edit';
					$_SESSION['msg']['id']	= $bid;
					$this->_redirect('/error');
				}
			}		    
		    
		} 

		$totalBlogs = $tbBlogs->countAllUserBlogs($uid);

		$listUid = array('lst_uid' => $uid);
		$oauthData = Util::oauthGetApi('http://localhost:3000/api/v1/users', $listUid, 'GET');
		
		$userInfo = array();
		if(!empty($oauthData) && is_array($oauthData)){
			$userInfo['fullname']   = $oauthData[$uid]['fullname'];
			$userInfo['uid']		= $uid;
			$userInfo['avatar']		= $oauthData[$uid]['avatar'];
			$userInfo['profile_url'] = $oauthData[$uid]['profile_url'];
		}

		$this->view->assign('totalBlog', $totalBlogs);
		$this->view->assign('error', $error);
		$this->view->assign('uid', $uid);
		$this->view->assign('usid', $uid);
		$this->view->assign('userInfo', $userInfo);
		$this->view->assign('title', $title);
		$this->view->assign('content', $content);	

	}

	public function delAction(){	

		$request = $this->getRequest();
		$uid = $_SESSION['logginUser']['uid'];
		$bid = $request->getParam("bid", null);

		$tbBlogs = new User_Model_Blogs();

		$blog = $tbBlogs->getBlogById($bid);
		$result = 0;
		if (!empty($blog) && $uid == $blog[0]['uid']){
			$result = $tbBlogs->deleteBlog($bid);	
		}

		if($result == 1){		
			$_SESSION['msg']['result'] = 1;
		}else{
			$_SESSION['msg']['result'] = 0;			
		}
		$_SESSION['msg']['action'] = 'del';
		$_SESSION['msg']['id']	= $blog[0]['uid'];

		$this->_redirect('/error');			
	}		
}